package com.qf.grabtickets.service.impl;


import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.canstants.Constants;
import com.qf.entity.User;

import com.qf.grabtickets.mapper.TUserMapper;
import com.qf.grabtickets.service.ITUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljc
 * @since 2023-03-10
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, User> implements ITUserService {

    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public String gettoken(Integer id) throws UnsupportedEncodingException {

        String token = (String) redisTemplate.opsForValue().get(Constants.JWT_CACHE_TOKEN_KEY + id);

        if (token!=null){

            return token;
        }

         token = createToken(id);

        redisTemplate.opsForValue().set(Constants.JWT_CACHE_TOKEN_KEY + id,token,60, TimeUnit.SECONDS);


        return token;
    }

    public String createToken(Integer id) throws UnsupportedEncodingException {

        String jwtToken = JWT.create().setSubject(id.toString())
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60))
                .setKey(Constants.SECRET.getBytes("utf-8"))
                .sign();

        return jwtToken;
    }
}
